package cz.muni.fi.pa165.sportclubmanager.client.modules.player;

import cz.muni.fi.pa165.sportclubmanager.service.player.PlayerDTO;
import cz.muni.fi.pa165.sportclubmanager.service.player.PlayerWebService;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Greegus
 */
public class PlayerListPanel extends javax.swing.JPanel {

    private List<PlayerDTO> players;

    /**
     * Creates new form ageCategoryListPanel
     */
    public PlayerListPanel() {
        initComponents();
        jProgressBar1.setVisible(false);
        reloadPlayersTable();
    }

    public class ReloadPlayersWorker extends SwingWorker<Integer, Integer> {

        @Override
        protected Integer doInBackground() throws Exception {
            try {
                players = new PlayerWebService().getPlayerServiceImplPort().findAll();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(PlayerListPanel.this,
                        "Error loading players",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);
                return 1;
            }
            DefaultTableModel tableModel = (DefaultTableModel) table.getModel();

            while (tableModel.getRowCount() > 0) {
                tableModel.removeRow(0);
            }

            SimpleDateFormat df = new SimpleDateFormat();
            df.applyPattern("yyyy.MM.dd");

            for (PlayerDTO player : players) {
                tableModel.addRow(new Object[]{
                            player.getFirstName(),
                            player.getLastName(),
                            df.format(player.getBirthDate().toGregorianCalendar().getTime()).toString(),
                            player.getHeight(),
                            player.getWeight(),
                            player.getId()
                        });
            }
            return 0;
        }

        @Override
        protected void done() {
            super.done();
            jProgressBar1.setIndeterminate(false);
            jProgressBar1.setVisible(false);
            refreshButton.setEnabled(true);
        }
    }

    public void reloadPlayersTable() {
        ReloadPlayersWorker worker = new ReloadPlayersWorker();
        jProgressBar1.setVisible(true);
        jProgressBar1.setIndeterminate(true);
        refreshButton.setEnabled(false);
        worker.execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        editMenuItem1 = new javax.swing.JMenuItem();
        deleteMenuItem1 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        addButton = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        refreshButton = new javax.swing.JButton();

        editMenuItem1.setText("Edit player");
        editMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuItem1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(editMenuItem1);

        deleteMenuItem1.setText("Delete player");
        deleteMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItem1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(deleteMenuItem1);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Last name", "Birth date", "Height", "Weight"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.setFillsViewportHeight(true);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tableMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        addButton.setText("Add new player");
        addButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                openNewPlayerForm(evt);
            }
        });

        refreshButton.setText("Refresh list");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(addButton)
                        .addComponent(refreshButton))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void openNewPlayerForm(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openNewPlayerForm
        PlayerForm form = new PlayerForm(this);
    }//GEN-LAST:event_openNewPlayerForm

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        if (evt.getClickCount() == 2 && !evt.isConsumed()) {
            evt.consume();

            int rowindex = table.getSelectedRow();

            if (rowindex < 0) {
                return;
            }

            rowindex = table.convertRowIndexToModel(rowindex);

            PlayerForm form = new PlayerForm(players.get(rowindex),this);
        }
    }//GEN-LAST:event_tableMouseClicked

    private void tableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMousePressed
        int r = table.rowAtPoint(evt.getPoint());

        if (r >= 0 && r < table.getRowCount()) {
            table.setRowSelectionInterval(r, r);
        } else {
            table.clearSelection();
        }

        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        if (evt.isPopupTrigger() && evt.getComponent() instanceof JTable) {
            jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_tableMousePressed

    private void tableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseReleased
        tableMousePressed(evt);
    }//GEN-LAST:event_tableMouseReleased

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        reloadPlayersTable();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void editMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuItem1ActionPerformed
        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        rowindex = table.convertRowIndexToModel(rowindex);

        PlayerForm form = new PlayerForm(players.get(rowindex),this);
    }//GEN-LAST:event_editMenuItem1ActionPerformed

    private void deleteMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItem1ActionPerformed
        int rowindex = table.getSelectedRow();

        if (rowindex < 0) {
            return;
        }

        rowindex = table.convertRowIndexToModel(rowindex);

        new DeletePlayerDialog(players.get(rowindex), this);
    }//GEN-LAST:event_deleteMenuItem1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JMenuItem deleteMenuItem1;
    private javax.swing.JMenuItem editMenuItem1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton refreshButton;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
